package com.szbmyoubao.app.ui.version

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.szbmyoubao.app.view.dialog.VersionUpdateDialog
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.CommonUtils
import com.ellecity06.cwhiskymall.databinding.ActivityVersionUpdateBinding

/**
 * @author ellecity06
 * @time 2024/11/1 11:01
 * @des
 */
class VersionUpdateActivity :
    BaseMvvmActivity<ActivityVersionUpdateBinding, VersionUpdateViewModel>() {
    override fun inflateBinding(): ActivityVersionUpdateBinding {
        return ActivityVersionUpdateBinding.inflate(layoutInflater)
    }

    @SuppressLint("SetTextI18n")
    override fun initialize(savedInstanceState: Bundle?) {
        title = "版本更新"
        binding.tvVersion.text = "Version: ${CommonUtils.getVersion(this)}"
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(VersionUpdateIntent.FetchLastVersion)
        }
        binding.tvUpdate.setOnClickListener {
            lifecycleScope.launchWhenCreated {
                viewModel.intentChannel.send(VersionUpdateIntent.ShowUpdateDialog)
            }
        }

    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is VersionUpdateState.Error -> {
                    binding.tvUpdate.isEnabled = false
                    binding.tvUpdate.text = "已经是最新版本"
                }
                is VersionUpdateState.Success -> {
                    binding.tvUpdate.isEnabled = it.isEnabled
                    binding.tvUpdate.text = if (it.isEnabled) "版本更新" else "已经是最新版本"


                }
                is VersionUpdateState.ShowDialog -> {
                    VersionUpdateDialog(this, it.data).show()
                }
            }
        }
    }
}